package com.starbaba.collaborate.service.impl;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.starbaba.base.service.CommProductChannelService;
import com.starbaba.base.service.CommProductPrdidService;
import com.starbaba.base.service.RegisterRecommendActivityService;
import com.starbaba.base.service.impl.CommProductChannelServiceImpl;
import com.starbaba.base.service.impl.CommProductPrdidServiceImpl;
import com.starbaba.base.service.impl.RegisterRecommendActivityServiceImpl;
import com.starbaba.collaborate.db.LoanCollaborateModel;
import com.starbaba.collaborate.model.*;
import com.starbaba.collaborate.service.CollaborateService;
import com.starbaba.core.web.page.PageRequest;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;
import com.tuanzi.server.loan_base.model.db.stat.StatCommActivityRegister;
import com.tuanzi.server.loan_base.util.DateUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CollaborateServiceImpl implements CollaborateService {
	private BaseDao dao = new BaseDao(Constant.LOAN_STAT_DB_POOL);

	// 修改合作方系数
	@Override
	public CollaborateResult updateCollaborateInof(String username, String channel, Integer ratio) {
		
		CollaborateResult result = new CollaborateResult();
		
		if(!StringUtils.isEmpty(username)&&!StringUtils.isEmpty(channel)){
			try {
				insertChannel(channel);//添加用户时添加对应的渠道系数,存在，不添加,默认为100
				insertUser(result, username, channel); //添加用户渠道
			} catch (AppException e) {
				LogService.error("合作方信息添加错误", e);
				e.printStackTrace();
			}
		}
		
		if(!StringUtils.isEmpty(channel)&&null!=ratio){
			try {
				updateRatioByChannelID(result, channel, ratio);
			} catch (AppException e) {
				LogService.error("合作方系数配置错误", e);
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	/**
	 * 保存用户信息
	 * @param channel 渠道
	 */
	private void insertChannel(String channel){
		String cr_sql="insert into collaborate_channel_ratio (channel_id) values(?)";
		String sql_exist="select count(channel_id) from collaborate_channel_ratio where channel_id=?";
		
		try {
			int num = dao.getInt(sql_exist, channel);
			
			if(num>0){ //存在，不做操作
				return;
			}else{ //添加
				dao.add(cr_sql, channel);
			}		
			
		} catch (AppException e) {
			LogService.error(e);
			e.printStackTrace();
		}
	}

	// 取得合作方详情列表
	@SuppressWarnings("rawtypes")
	@Override
	public List getCollaborateList(Integer start, Integer length, PageResponse pageResponse,
			Map<String, Object> paramsMap, String userid) throws Exception {

		// 获取参数
		String startTime = (String) paramsMap.get("startTime");// 开始时间
		String endTime = (String) paramsMap.get("endTime");// 结束时间
		String channel_code = (String) paramsMap.get("channel_code");
		StringBuilder whereParams = new StringBuilder();
		if (StringUtils.isNotEmpty(startTime)) {
			whereParams.append("and ctime >= '" + startTime + "' ");
		}
		if (StringUtils.isNotEmpty(endTime)) {
			whereParams.append("and ctime <= '" + endTime + "' ");
		}
		if (StringUtils.isNotEmpty(channel_code)) {
			whereParams.append("and channel_code = '" + channel_code + "' ");
		}
		
		StringBuffer listSql = new StringBuffer();
		listSql.append("select * from loan_collaborate_info where 1=1 AND  channel_code in (select channel from collaborate_user_info where username=? ) and username=? ");
		listSql.append(whereParams.toString());
		listSql.append(" order by ctime desc");
		
		String listCount="select count(id) from ("+listSql+") z ";
		
		if (listSql.length() > 0 && start >= 0 && length > 0) {
			listSql.append(" LIMIT " + start + ", " + length);
		}
		
		List<LoanCollaborateModel> list = dao.list(listSql.toString(), LoanCollaborateModel.class, userid,userid);
		int count = dao.getInt(listCount,userid,userid);
		pageResponse.setITotalRecords(count);
		pageResponse.setITotalDisplayRecords(count);
		return list;
	}

	@Override
	public String exportCollaborateListCVS(List<LoanCollaborateModel> list) {
		StringBuilder builder = new StringBuilder();
		builder.append("日期,产品,渠道,新增数,新增时间注册用户数,新增时间注册率\r\n");
		for (LoanCollaborateModel vo : list) {
			builder.append(vo.getCtime()).append(",");
			// builder.append(vo.getPlatform()).append(",");
			builder.append(vo.getPrid()).append(",");
			builder.append(vo.getChannel()).append(",");
			builder.append(vo.getIncreased()).append(",");
			builder.append(vo.getNewRegisterde()).append(",");
			builder.append(vo.getNewRegisterdeRate()).append(",");
			builder.append("\r\n");
		}
		return builder.toString();
	}

	//获取用户渠道信息
	@Override
	public void showpage(Map<String, Object> paramsMap, String userid) {
		String sql="SELECT b.channel_name  as channel,a.channel_id as channel_code FROM collaborate_channel_user a LEFT JOIN  "
				+ "loan.comm_product_channel b on a.channel_id=b.channel_code where a.username=?";
		try {
			List<CollaborateModelBean> list = dao.list(sql, CollaborateModelBean.class, userid);
			paramsMap.put("channelList", list);
		} catch (AppException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param result 返回结果对象
	 * @param username  用户名
	 * @param channel_id  渠道id
	 * @return 结果对象
	 * @throws AppException
	 */
	private CollaborateResult insertUser(CollaborateResult result, String username, String channel_id) throws AppException{
		String uc_sql="insert into collaborate_channel_user (username,channel_id) values(?,?)";
		String uc_exist="select count(username) from collaborate_channel_user where username=? and channel_id=?";
		
		int num = dao.getInt(uc_exist, username, channel_id);
		
		if(num>0){
			result.setResult("对应渠道的合作方已经存在！");
		}else{
			dao.add(uc_sql, username,channel_id);
			result.setResult("用户添加成功！");
		}
		return result;
	}
	
	/**
	 * 
	 * @param result
	 * @param channel_id 渠道id
	 * @param ratio 配置的系数
	 * @return
	 * @throws AppException
	 */
	private CollaborateResult updateRatioByChannelID(CollaborateResult result, String channel_id, Integer ratio) throws AppException{
		String cr_sql="insert into collaborate_channel_ratio (channel_id,tomorrowRatio) values(?,?)";
		String sql_exist="select count(channel_id) from collaborate_channel_ratio where channel_id=?";
		String update_sql="update collaborate_channel_ratio set tomorrowRatio=? where channel_id=?";
		
		int num = dao.getInt(sql_exist, channel_id);
		
		if(num>0){
			dao.update(update_sql, ratio,channel_id);
			result.setResult("系数更新成功！");
		}else{
			dao.add(cr_sql, channel_id,ratio);
			result.setResult("渠道添加成功！");
		}
		
		return result;
	}

	
	//跳转到合作方注册信息页面
	@Override
	public void showCollabPage(Map<String, Object> paramsMap, String userid) {
		String channelSql="SELECT b.channel_name ,a.channel_id FROM collaborate_channel_user a LEFT JOIN  "
				+ "loan.comm_product_channel b on a.channel_id=b.channel_code where username=?";
		String productSql="select prdid as product_id,name as product_name from loan.comm_product_prdid where prdid in (8000,8002)";
		String activityTypeSql="select activity_type as activity_type_id,activity_type_name from loan.register_recommend_activity";
		
		try {
			List<ConditionModel> channelList = dao.list(channelSql, ConditionModel.class, userid);
			List<ConditionModel> productList = dao.list(productSql, ConditionModel.class);
			List<ConditionModel> activityTypeList = dao.list(activityTypeSql, ConditionModel.class);
			
			paramsMap.put("channelList", channelList);
			paramsMap.put("productList", productList);
			paramsMap.put("activityTypeList", activityTypeList);
		} catch (AppException e) {
			e.printStackTrace();
		}
		
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<StatCommActivityRegister> getCollabRegisterList(PageRequest pagerequest, PageResponse pageResponse,
			Map<String, Object> paramsMap, String userid) throws Exception {
		List<StatCommActivityRegister> list=new ArrayList<StatCommActivityRegister>();
		
		int start = pagerequest.getIDisplayStart();
		int length = pagerequest.getIDisplayLength();
			
		//当前时间
		String curDate = DateUtils.getCurrentDate();
		
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT a.* FROM ");
		sql.append("(SELECT cdate,prd_id,platform,channel,activity_type,activity_id,external_register_count,external_new_register_count,app_activate_count,app_activate_count_phone,login_count");
		sql.append(" FROM stat_comm_activity_register");
		sql.append(" WHERE cdate = '"+curDate+"'AND channel IN (SELECT channel_id FROM collaborate_channel_user WHERE username = ? )");
		sql.append(" UNION ALL");
		sql.append(" select cdate,prd_id,platform, channel,activity_type,activity_id,external_register_count,external_new_register_count,app_activate_count,app_activate_count_phone,login_count from stat_collaborate_register");
		sql.append(" where channel in(select channel_id from collaborate_channel_user where username= ? )) a where 1=1");
		//添加查询条件
		addRegisterCondition(paramsMap, sql);
		sql.append(" ORDER BY a.cdate desc");
		
		//PageBean pageBean = new PageBean(pagerequest.getIDisplayStart()/pagerequest.getIDisplayLength()+1, pagerequest.getIDisplayLength());
		//list = dao.listByPage(pageBean, sql.toString(), StatCommActivityRegister.class, userid,userid);
		int count = dao.getInt("select count(1) from ( " + sql.toString() +" ) z", userid, userid);
		
		if(sql.length()>0&&start>=0&&length>0){
			sql.append(" limit "+start+" ,"+length);
		}
		
		 list = dao.list(sql.toString(),StatCommActivityRegister.class, userid, userid);
		
		setproperties(list, curDate);
		
		pageResponse.setITotalDisplayRecords(count);
		pageResponse.setITotalRecords(count);
		
		return list;
	}
	
	/**
	 * 添加查询条件
	 * @param paramsMap
	 * @param sql
	 */
	private void addRegisterCondition(Map<String, Object> paramsMap, StringBuilder sql){
		String startTime = (String) paramsMap.get("startTime");
		String endTime = (String) paramsMap.get("endTime");
		String platfrom = (String) paramsMap.get("platfrom");
		String product = (String) paramsMap.get("product");
		String channel = (String) paramsMap.get("channel");
		String activityType = (String) paramsMap.get("activityType");
		String activity_id = (String) paramsMap.get("activity_id");
		
		if(!StringUtils.isEmpty(startTime)){
			sql.append(" and a.cdate>='"+startTime+"'");
		}
		if(!StringUtils.isEmpty(endTime)){
			sql.append(" and a.cdate<='"+endTime+"'");
		}
	
		if(!StringUtils.isEmpty(platfrom)){
			sql.append(" and a.platform='"+platfrom+"'");
		}
		if(!StringUtils.isEmpty(product)){
			sql.append(" and a.prd_id='"+product+"'");
		}
		if(!StringUtils.isEmpty(channel)){
			sql.append(" and a.channel='"+channel+"'");
		}
		if(!StringUtils.isEmpty(activityType)){
			sql.append(" and a.activity_type='"+activityType+"'");
		}
		if(!StringUtils.isEmpty(activity_id)){
			sql.append(" and a.activity_id='"+activity_id+"'");
		}
	}
	
	//查询所有渠道的显示系数
	private List<CollaborateChannelRatio> getAllTodayRatio(){
		String sql="select channel_id ,ratio,show_type from collaborate_channel_ratio";
		
		List<CollaborateChannelRatio> list=new ArrayList<CollaborateChannelRatio>();
		
		try {
			list = dao.list(sql, CollaborateChannelRatio.class);
		} catch (AppException e) {
			LogService.error(e);
			e.printStackTrace();
		}
		return list;
	}	
	
	private List<StatCommActivityRegister> setproperties(List<StatCommActivityRegister> list, String curDate){
		CommProductPrdidService prdidService= new CommProductPrdidServiceImpl();
		CommProductChannelService channelService=new CommProductChannelServiceImpl();
		RegisterRecommendActivityService activityService=new RegisterRecommendActivityServiceImpl();
		
	    Map<String, String> prdidMap = prdidService.getCommProductPrdidMap();
		Map<String, String> channelMap = channelService.getCommProductChannelMap();
		Map<String, String> activityMap = activityService.getRegisterRecommendActivityMap();
		
		List<CollaborateChannelRatio> ratios = getAllTodayRatio();

		for (StatCommActivityRegister register : list) {
			for (CollaborateChannelRatio channelratio : ratios) {
				if(register.getChannel().equals(channelratio.getChannel_id())){
					Integer ratio = channelratio.getRatio();
					Integer show_type = channelratio.getShow_type();
					
					//配置表的显示类型
					if(1==show_type){ //显示注册人数1,置空注册人数2,3,4,5

						if(register.getCdate().equals(curDate)){ //今天且登录数据大于20 的数据要乘以系数
							register.setExternal_new_register_count(getKLAfterCount(register.getExternal_new_register_count(), ratio));
						}
						register.setApp_activate_count(null);
						register.setApp_activate_count_phone(null);
						register.setLogin_count(null);
						register.setExternal_register_count(null);
						
					}else if(2==show_type){ //显示注册人数2,置空注册人数1,3,4,5
						String platform = register.getPlatform();
						if("ios".equals(platform)){//苹果的app激活数需要的是按手机号的app注册数
							Integer count_phone = register.getApp_activate_count_phone();
							register.setApp_activate_count(count_phone);
						}

						if(register.getCdate().equals(curDate)){
							register.setApp_activate_count(getKLAfterCount(register.getApp_activate_count(), ratio));
						}

						register.setExternal_register_count(null);
						register.setExternal_new_register_count(null);
						register.setLogin_count(null);
						register.setApp_activate_count_phone(null);
						
					}else if(3 == show_type){ //显示注册人数3，置空注册1,2,4,5

						if(register.getCdate().equals(curDate)){
							register.setApp_activate_count_phone(getKLAfterCount(register.getApp_activate_count_phone(), ratio));
						}
						
						register.setExternal_new_register_count(null);
						register.setApp_activate_count(null);
						register.setLogin_count(null);
						register.setExternal_register_count(null);
						
					}else if(4 == show_type){ //注册人数4

						if(register.getCdate().equals(curDate)){
							register.setLogin_count(getKLAfterCount(register.getLogin_count(), ratio));
						}
						register.setExternal_new_register_count(null);
						register.setApp_activate_count(null);
						register.setApp_activate_count_phone(null);
						register.setExternal_register_count(null);

					}else if(5 == show_type){
						if(register.getCdate().equals(curDate)){
							register.setExternal_register_count(getKLAfterCount(register.getExternal_register_count(), ratio));
						}

						register.setExternal_new_register_count(null);
						register.setApp_activate_count(null);
						register.setApp_activate_count_phone(null);
						register.setLogin_count(null);

					} else{ //全表显示
						String platform = register.getPlatform();
						if("ios".equals(platform)){ //苹果的app激活数需要的是按手机号的app注册数
							Integer app_activate_count_phone = register.getApp_activate_count_phone();
							register.setApp_activate_count(app_activate_count_phone);
						}

						if(register.getCdate().equals(curDate)){
							register.setExternal_new_register_count(getKLAfterCount(register.getExternal_new_register_count(), ratio));
							register.setApp_activate_count(getKLAfterCount(register.getApp_activate_count(), ratio));
							register.setApp_activate_count_phone(getKLAfterCount(register.getApp_activate_count_phone(), ratio));
							register.setLogin_count(getKLAfterCount(register.getLogin_count(), ratio));
							register.setExternal_register_count(getKLAfterCount(register.getExternal_register_count(), ratio));
						}
					}
				}
			}

			String prdid = register.getPrd_id();
			String channel = register.getChannel();
			String activity_type = register.getActivity_type();
			register.setPrd_name(prdidMap.get(prdid));
			register.setChannel_name(channelMap.get(channel));
			register.setActivity_type_name(activityMap.get(activity_type));	
		}
		return list;
	}

	private Integer getKLAfterCount(Integer baseCount, Integer ratio){
		if(null == baseCount || null == ratio){
			return null;
		}

		final int ratioBegin = 10; //扣量的开始的基准数，超过这个数据执行配置的系数进行扣量
		int klCount = baseCount - ratioBegin;
		if(klCount > 0){
			int klCountAfter = Math.round((float) klCount * ratio / 100);
			return ratioBegin + klCountAfter;
		}

		return baseCount;
	}
	
	//跳转到表展示配置列表
	@Override
	public void showTableTypePage(Map<String, Object> paramsMap) {
		String sql="SELECT a.channel_id,b.channel_name FROM collaborate_channel_user a LEFT JOIN loan.comm_product_channel b on a.channel_id=b.channel_code ";
		
		try {
			List<ConditionModel> list = dao.list(sql, ConditionModel.class);
			paramsMap.put("channelList", list);
		} catch (AppException e) {
			LogService.error(e);
			e.printStackTrace();
		}
		
	}
	
	//查询合作方列表
	@SuppressWarnings("rawtypes")
	@Override
	public List<CollaborateInfo> getCollaborateChannelRatioList(PageRequest pagerequest,
			PageResponse pageResponse, Map<String, Object> paramsMap) throws Exception {
		StringBuilder sql=new StringBuilder();
		sql.append("select a.channel_id as channel,a.ratio,a.tomorrowRatio,a.show_type,b.username from collaborate_channel_ratio a LEFT JOIN collaborate_channel_user b ON a.channel_id=b.channel_id");
		String username = (String) paramsMap.get("username");
		if(StringUtils.isNotBlank(username)){
			sql.append(" where username ='" + username + "'");
		}

		int start = pagerequest.getIDisplayStart();
		int length = pagerequest.getIDisplayLength();
		
		int count = dao.getInt("select count(1) from ("+sql.toString()+") z");
		
		if(sql.length()>0&&start>=0&&length>0){
			sql.append(" limit "+start+" ,"+length);
		}
		
		List<CollaborateInfo> list = dao.list(sql.toString(),CollaborateInfo.class);
		
		pageResponse.setITotalDisplayRecords(count);
		pageResponse.setITotalRecords(count);
		
		return list;
	}
	
	
	//修改合作方展示表信息
	@Override
	public CollaborateResult updatetable(String channel_id, String table_type){	
		CollaborateChannelRatio bean = new CollaborateChannelRatio();
		bean.setChannel_id(channel_id);
		bean.setShow_type(Integer.valueOf(table_type));
		
		CollaborateResult result = new CollaborateResult();
		try {
			
			dao.update(bean, new String[]{"channel_id"});
			
			result.setResult("操作成功！");
			
		} catch (AppException e) {
			LogService.error(e);
			result.setResult("error，操作失败！");
		}
		return result;
	}

	@Override
	public String exportCollaborateRegisterListCVS(List<StatCommActivityRegister> list) {
		StringBuilder builder = new StringBuilder();
		builder.append("日期,产品,渠道,平台,活动ID,注册人数1,注册人数2,注册人数3,注册人数4,注册人数5\r\n");
		for (StatCommActivityRegister vo : list) {
			builder.append(vo.getCdate()).append(",");
			builder.append(vo.getPrd_name()).append(",");
			builder.append(vo.getChannel_name()).append(",");
			builder.append(vo.getPlatform()).append(",");
			builder.append(vo.getActivity_id()).append(",");
			builder.append(vo.getExternal_new_register_count()).append(",");
			builder.append(vo.getApp_activate_count()).append(",");
			builder.append(vo.getApp_activate_count_phone()).append(",");
			builder.append(vo.getLogin_count()).append(",");
			builder.append(vo.getExternal_register_count()).append(",");
			builder.append("\r\n");
		}
		return builder.toString();
	}
	
}
